function getCookie(name)
{
    let arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr===document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

function clearCookies() {
    var currentDate = new Date();
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf('=');
        var cookieName = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = cookieName.trim() + "=; expires=" + currentDate.toUTCString() + "; path=/;";
    }
}

class Utils {

    AjaxGet (url, func) {
        let sing = getCookie("sing");
        let user = getCookie("user");
        console.log(sing);
        console.log(user);
        $.ajax({
            type: "get",
            url:  url,
            data: "",
            dataType: 'json',
            headers: {
                token: sing,
                user: user,
            },
            async: true,
            success: function(data){
                func(data);
            },
            error: function(xhr,textStatus) {
                console.log(xhr, textStatus);
                if (xhr.status===403) {
                    clearCookies()
                    window.location.href = "/out"
                }
            }
        });
    }

    AjaxGetNotAsync(url, func) {
        let sing = getCookie("sing");
        let user = getCookie("user");
        $.ajax({
            type: "get",
            url:  url,
            data: "",
            dataType: 'json',
            headers: {
                token: sing,
                user: user,
            },
            async: false,
            success: function(data){
                func(data);
            },
            error: function(xhr,textStatus) {
                console.log(xhr, textStatus);
            }
        });
    }

    AjaxPost(url, param, func) {
        let sing = getCookie("sing");
        let user = getCookie("user");
        $.ajax({
            type: "post",
            url:  url,
            data: JSON.stringify(param),
            dataType: 'json',
            headers: {
                token: sing,
                user: user,
            },
            async: true,
            success: function(data){
                func(data);
            },
            error: function(xhr,textStatus) {
                console.log(xhr, textStatus);
            }
        });
    }

    ToastShow(msg) {
        const toastLiveExample = $('#liveToast')
        const toast = new bootstrap.Toast(toastLiveExample)
        $("#liveToastMsg").empty(msg);
        $("#liveToastMsg").append(msg);
        toast.show()
    }
}
